<template>
  <view>
    <!-- 全局 Toast 通知组件 -->
    <ToastNotification 
      ref="globalToast"
      :visible="toastVisible"
      :title="toastTitle"
      :message="toastMessage"
      :type="toastType"
      :icon="toastIcon"
      :duration="toastDuration"
      @close="handleToastClose"
    />
  </view>
</template>

<script>
import chatService from '@/utils/websocket-chat-service.js'
import { recordLog } from '@/utils/api-logger.js'
import appStateManager from '@/utils/app-state-manager.js'
import notificationService from '@/utils/notification-service.js'
import SMSReaderService from '@/utils/sms-reader-service.js'
import PackageService from '@/utils/package-service.js'
import wgtHotUpdate from '@/utils/wgt-hot-update.js'
import ToastNotification from '@/components/ToastNotification.vue'
import toastManager from '@/utils/toast-manager.js'

export default {
  components: {
    ToastNotification
  },
  data() {
    return {
      toastVisible: false,
      toastTitle: '提示',
      toastMessage: '',
      toastType: 'info',
      toastIcon: '',
      toastDuration: 2500
    }
  },
  onLaunch: async function() {
		console.log('App Launch')
		
		// 注册全局 Toast 实例
		this.$nextTick(() => {
			toastManager.setToastInstance(this)
		})
		
		// 初始化版本信息（确保版本从系统获取并保存到本地存储）
		try {
			await wgtHotUpdate.init()
			console.log('App启动时版本信息初始化完成')
		} catch (error) {
			console.error('App启动时版本信息初始化失败:', error)
		}
		
		// 惰性初始化：仅在需要时由页面初始化，这里不强制
		try {
			await appStateManager.checkServerHealth()
			console.log('App启动时服务器健康检查完成')
			
			// 初始化通知系统
			this.initNotificationSystem()
		} catch (error) {
			console.error('App启动时服务器健康检查失败:', error)
		}
	},
	
	methods: {
		// 初始化通知系统
		async initNotificationSystem() {
			try {
				// 请求通知权限
				const granted = await notificationService.requestPermission()
				console.log('通知权限状态:', granted ? '已授权' : '未授权')

				// 更新通知角标
				notificationService.updateUnreadBadge()
				console.log('通知角标已更新')

				// 初始化短信监听服务（仅在已授权的情况下）
				this.initSmsListener()
			} catch (error) {
				console.error('初始化通知系统失败:', error)
			}
		},

		// 初始化短信监听服务
		async initSmsListener() {
			try {
				// #ifdef APP-PLUS
				const hasPermission = await SMSReaderService.checkPermission()
				if (hasPermission) {
					// 启动短信监听，并设置回调处理新短信
					const started = SMSReaderService.startSMSListener((smsExpressInfo) => {
						// 收到快递短信时自动创建或更新包裹
						this.handleNewExpressSMS(smsExpressInfo)
					})
					if (started) {
						console.log('短信监听服务已启动')
					} else {
						console.log('短信监听服务启动失败')
					}
				} else {
					console.log('未授权短信读取权限，跳过短信监听')
				}
				// #endif
			} catch (error) {
				console.error('初始化短信监听服务失败:', error)
			}
		},

		// 处理新的快递短信
		async handleNewExpressSMS(smsExpressInfo) {
			try {
				console.log('收到快递短信:', smsExpressInfo)
				
				// 自动创建或更新包裹
				const pkg = await PackageService.updateOrCreateFromSMS(smsExpressInfo)
				
				// 显示通知
				notificationService.showNotification({
					title: '快递包裹更新',
					body: `快递单号：${pkg.trackingNumber}\n状态：${pkg.status}`,
					data: {
						type: 'package_update',
						packageId: pkg.id
					}
				})
				
				console.log('包裹已自动添加/更新:', pkg)
			} catch (error) {
				console.error('处理快递短信失败:', error)
			}
		},
		// Toast 显示方法（供 toast-manager 调用）
		show(options) {
			this.toastTitle = options.title || '提示'
			this.toastMessage = options.message || ''
			this.toastType = options.type || 'info'
			this.toastIcon = options.icon || ''
			this.toastDuration = options.duration || 2500
			this.toastVisible = true
		},
		// Toast 隐藏方法
		hide() {
			this.toastVisible = false
		},
		// Toast 关闭事件处理
		handleToastClose() {
			this.toastVisible = false
		}
	},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		// 保持连接不断开，便于跨页接收在线状态
		},
		onUnload: async function() {
			try { await chatService.disconnect() } catch (e) {}
		},
		onError: async function(err) {
			try { await chatService.disconnect() } catch (e) {}
			try { recordLog({ type: 'runtime', method: 'APP', url: 'app.onError', status: 'ERROR', success: false, errorMessage: (err && err.message) || String(err), durationMs: 0 }) } catch (e2) {}
		}
	}
</script>

<style>
	/*每个页面公共css */
</style>
